package algorithm.string.baisc;

public class BruteForce01 {

    /**
     * 蛮力匹配 - 改进
     */
    public static int indexOf2(String text, String pattern) {
        if (text == null || pattern == null) return -1;
        char[] textChars = text.toCharArray();
        int tLen = textChars.length;
        char[] patternChars = pattern.toCharArray();
        int pLen = patternChars.length;
        if (tLen == 0 || pLen == 0 || tLen < pLen) return -1;
        int pi = 0, ti = 0;
        while (pi < pLen && ti - pi <= tLen - pLen) { // ti - pi <= tlen - plen 是关键
            if (textChars[ti] == patternChars[pi]) {
                ti++;
                pi++;
            } else {
                ti = ti - pi + 1;
                // ti -= pi - 1;
                pi = 0;
            }
        }
        return pi == pLen ? ti - pi : -1;
    }

    /**
     * 蛮力匹配 O(mn)
     */
    public static int indexOf(String text, String pattern) {
        // 检测数据合法性
        if (text == null || pattern == null) return -1;
        char[] textChars = text.toCharArray();
        int tLen = textChars.length;
        char[] patternChars = pattern.toCharArray();
        int pLen = patternChars.length;
        if (tLen == 0 || pLen == 0 || tLen < pLen) return -1;
        int pi = 0, ti = 0;
        while (pi < pLen && ti < tLen) {
            if (textChars[ti] == patternChars[pi]) {
                ti++;
                pi++;
            } else {
                ti = ti - pi + 1;
                // ti -= pi - 1;
                pi = 0;
            }
        }
        return pi == pLen ? ti - pi : -1;
    }
}
